package com.atguigu.gmall.cart.service.impl;

import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ProductFeignClient productFeignClient;

    @Override
    public void addToCart(Long skuId, Integer skuNum, String userId) {

        String cartKey = getCartKey(userId);

        CartInfo cartInfoExist = (CartInfo) this.redisTemplate.opsForHash().get(cartKey,skuId.toString());

        //判断
        if(cartInfoExist!=null){
            //当前的购物车中是否有当前购物项
            cartInfoExist.setSkuNum(cartInfoExist.getSkuNum()+skuNum);
            if(cartInfoExist.getIsChecked().intValue()==0){
                cartInfoExist.setIsChecked(1);
            }
            //赋值实时价格数据
            cartInfoExist.setSkuPrice(productFeignClient.getSkuPrice(skuId));
            //重新赋值修改下时间
            cartInfoExist.setUpdateTime(new Date());
            //放入缓存
            this.redisTemplate.opsForHash().put(cartKey,skuId.toString(),cartInfoExist);

        }else {
            cartInfoExist = new CartInfo();
            //赋值操作
            SkuInfo skuInfo = this.productFeignClient.getSkuInfo(skuId);
            cartInfoExist.setSkuId(skuInfo.getId());
            cartInfoExist.setSkuName(skuInfo.getSkuName());
            cartInfoExist.setSkuNum(skuNum);
            //第一次加入购物车得数据和缓存中得数据是一样的
            cartInfoExist.setSkuPrice(productFeignClient.getSkuPrice(skuId));
            cartInfoExist.setCartPrice(productFeignClient.getSkuPrice(skuId));
            cartInfoExist.setImgUrl(skuInfo.getSkuDefaultImg());
            cartInfoExist.setUserId(userId);
            cartInfoExist.setCreateTime(new Date());
            cartInfoExist.setUpdateTime(new Date());
        }
        //放入缓存
        this.redisTemplate.opsForHash().put(cartKey,skuId.toString(),cartInfoExist);
    }

    @Override
    public List<CartInfo> getcartList(String userId, String userTempId) {

        List<CartInfo> cartInfoNoLoginList = new ArrayList<>();
        //登录
        if(!StringUtils.isEmpty(userId)){
            //登录，获取数据
            String cartKey = this.getCartKey(userId);
            BoundHashOperations<String,String,CartInfo> boundHashOperations = this.redisTemplate.boundHashOps(cartKey);

            if(!StringUtils.isEmpty(cartInfoNoLoginList)){
                cartInfoNoLoginList.stream().forEach( cartInfoNoLogin->{
                    if(boundHashOperations.hasKey(cartInfoNoLogin.getSkuId().toString())){
                        CartInfo cartInfoLogin = boundHashOperations.get(cartInfoNoLogin.getSkuId().toString());
                        cartInfoLogin.setSkuNum(cartInfoLogin.getSkuNum()+cartInfoNoLogin.getSkuNum());
                        //设置更新时间
                        cartInfoLogin.setUpdateTime(new Date());

                        if(cartInfoLogin.getIsChecked().intValue()==1 && cartInfoLogin.getIsChecked().intValue()==0){
                            cartInfoLogin.setIsChecked(1);
                        }
                        //将写好得对象写入缓存
                        boundHashOperations.put(cartInfoNoLogin.getSkuId().toString(),cartInfoNoLogin);
                    }else {
                        cartInfoNoLogin.setUserId(userId);
                        cartInfoNoLogin.setCreateTime(new Date());
                        cartInfoNoLogin.setUpdateTime(new Date());
                        boundHashOperations.put(cartInfoNoLogin.getSkuId().toString(),cartInfoNoLogin);
                    }
                } );
            }
            //删除为登录购物车集合数据
            this.redisTemplate.delete(this.getCartKey(userTempId));

            List<CartInfo> cartInfoLoginList = boundHashOperations.values();

            //做排序
            if(!StringUtils.isEmpty(cartInfoLoginList)){
                cartInfoLoginList.sort((o1,o2)->{
                    return DateUtil.truncatedCompareTo(o2.getUpdateTime(),o1.getUpdateTime(), Calendar.SECOND);
                });
            }
            return cartInfoLoginList;
        }

        //未登录
        if(!StringUtils.isEmpty(userTempId)){
            String cartKey = this.getCartKey(userTempId);
            cartInfoNoLoginList = this.redisTemplate.opsForHash().values(cartKey);
        }
        if(!StringUtils.isEmpty(cartInfoNoLoginList)){
            cartInfoNoLoginList.sort((o1,o2)->{
                //调用时间工具类
                return DateUtil.truncatedCompareTo(o2.getUpdateTime(),o1.getUpdateTime(), Calendar.SECOND);
            });
            //返回未登录购物车
            return cartInfoNoLoginList;
        }
      return new ArrayList<>();
    }

    @Override
    public void checkCart(Long skuId, Integer isChecked, String userId) {
        String cartKey = this.getCartKey(userId);
        CartInfo cartInfo  = (CartInfo) this.redisTemplate.boundHashOps(cartKey).get(skuId.toString());

        if(cartInfo != null){
            cartInfo.setIsChecked(isChecked);
            this.redisTemplate.boundHashOps(cartKey).put(skuId.toString(),cartInfo);
        }
    }

    @Override
    public void deleteCart(String userId, Long skuId) {
        String cartKey = this.getCartKey(userId);
        this.redisTemplate.boundHashOps(cartKey).delete(skuId.toString());
    }

    @Override
    public List<CartInfo> getCartCheckedList(String userId) {
        String cartKey = this.getCartKey(userId);
        List<CartInfo> cartInfoList = this.redisTemplate.boundHashOps(cartKey).values();
        cartInfoList.stream().filter(cartInfo -> {
            cartInfo.setSkuPrice(productFeignClient.getSkuPrice(cartInfo.getSkuId()));
            return cartInfo.getIsChecked().intValue()==1;
        }).collect(Collectors.toList());
        return cartInfoList;
    }


    private String getCartKey(String userId) {
        return RedisConst.USER_KEY_PREFIX + userId + RedisConst.USER_CART_KEY_SUFFIX;
    }


}
